/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class code5 {
    //二叉搜索树中第 K 小的元素
    public int count = 0;
    public int prev = 0;

    public void dfs(TreeNode root,int k) {
        //出口
        if(root==null) return;

        //左
        dfs(root.left,k);

        //中
        if(++count==k) {
            prev = root.val;
            return;
        }

        //右
        dfs(root.right,k);
    }
    public int kthSmallest(TreeNode root, int k) {
        dfs(root,k);
        return prev;
    }
}